package com.daervin.svc.common.utils;

import com.daervin.svc.common.dto.ShortUrlDTO;
import okhttp3.*;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author daervin
 * @version 1.0.0
 * @since 1.0.0
 */
public class ShortUrlUtil {
    private ShortUrlUtil() {
    }

    private static final String TOKEN = "8e61faf078b82db9766899362d35dfa7";
    private static final String URL = "https://dwz.cn/admin/v2/create";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static ShortUrlDTO getShortUrl(String longUrl) {
        OkHttpClient httpClient = new OkHttpClient();
        httpClient.newBuilder().connectTimeout(1, TimeUnit.SECONDS);

        try {
            RequestBody body = RequestBody.create(JSON, "{\"url\":\"" + longUrl + "\"}");
            Request.Builder builder = new Request.Builder();
            builder.url(URL).addHeader("Token", TOKEN).post(body);
            Response response = httpClient.newCall(builder.build()).execute();
            String info = response == null || response.body() == null ? null : response.body().string();
            if (StringUtils.isEmpty(info)) {
                return null;
            }
            return JsonUtil.toObject(info, ShortUrlDTO.class);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        ShortUrlDTO info = getShortUrl("https://dwz.cn/console/faq");
        System.out.println(info.toString());
    }
}
